<template>
  <div v-if="ready" class="l-rblock print-form">
    <div class="l-rblock print-form-design" v-show="!isPreview">
      <div class="print-form__components">
        <el-menu
          :collapse="true"
          default-active="1"
          style="text-align: center"
          @select="handleMenuClick"
        >
          <el-menu-item index="1" style="width: 56px">
            <i
              class="el-icon-copy-document"
              style="transform: rotateZ(320deg)"
            />
            <span slot="title">{{ $t('图层') }}</span>
          </el-menu-item>
          <el-menu-item
            index="2"
            style="border-bottom: 1px #dddddd solid; width: 56px"
          >
            <i class="el-icon-s-operation" />
            <span slot="title">{{ $t('数据模型') }}</span>
          </el-menu-item>
        </el-menu>
        <el-menu
          :collapse="true"
          style="text-align: center"
          @select="addComponent"
        >
          <el-menu-item
            v-for="item in components"
            :key="item.label"
            :index="item.type"
            style="width: 56px"
          >
            <i :class="item.icon" />
            <span slot="title">
              {{ item.label }}
            </span>
          </el-menu-item>
        </el-menu>
      </div>

      <l-layout
        class="l-tab-page"
        v-if="!lr_loadPage"
        :leftMove="false"
        :rightMove="false"
        :left="240"
        :right="304"
      >
        <template #left>
          <l-panel
            style="
                padding: 0;
                padding-left: 2px;
              "
            v-if="isLayer"
          >
            <template #title>{{ $t("图层") }}</template>
            <component-layer
              :list="pageActiveObj.components"
              :activeComponent="activeObj"
              :pageConfig="pageConfig"
              @copy="copyComponent"
              @delete="deleteComponent"
              @setActive="setComponentActive"
            />
          </l-panel>
          <l-panel
            style="
                padding: 0;
                padding-left: 2px;
              "
            v-else
          >
            <template #title>
              {{ $t("数据模型") }}
              <div class="tree-setting-btn">
                <el-button
                  @click="handOpenDbTable"
                  type="text"
                  icon="el-icon-plus"
                ></el-button>
              </div>
            </template>
            <component-db-table @delete="deleteDbTable" :list="dbtableList" />
          </l-panel>
        </template>

        <div class="l-rblock" style="padding-top: 48px;padding-bottom: 40px;">
          <header-tool
            :activeComponent="activeObj"
            :pageConfig="pageConfig"
            :pageHeight="pageHeight"
            :pageWidth="pageWidth"
            @setValue="setComponentValue"
            @clear="clearComponents"
            @preview="openPreview"
          />

          <body-design
            :pageConfig="pageConfig"
            :pageComponents="pageActiveObj.components"
            :headerComponents="headerComponents"
            :pageHeight="pageHeight"
            :pageWidth="pageWidth"
            :pageActive="pageActive"
            :pageNumbers="pages.length"
            :activeComponent="activeObj"
            :scale="scale"
            :gridShow="gridShow"
            :gridSize="gridSize"
            :ruleShow="ruleShow"
            @setActive="setComponentActive"
          />

          <footer-tool
            :scale.sync="scale"
            :pageActive.sync="pageActive"
            :pages="pages"
            :gridShow.sync="gridShow"
            :gridSize.sync="gridSize"
            :ruleShow.sync="ruleShow"
            @setActive="setComponentActive"
          />
        </div>

        <template #right>
          <l-panel
            :title="`属性设置(${activeObj ? activeObj.label : '页面'})`"
            style="padding:0;"
          >
            <div v-if="activeObj" class="print-page-config-panel">
              <component
                :is="activeObj.type + '-config'"
                :pageConfig="pageConfig"
                :config="activeObj.config"
                :dbtableList="dbtableList"
                :pageIndex="pageActive"
                :pageComponents="pageActiveObj.components"
              />
            </div>

            <!-- 页面设置 -->
            <page-config
              v-show="activeObj == null"
              :pageConfig="pageConfig"
              :pageNumbers="pages.length"
              ref="pageConfigForm"
            />
          </l-panel>
        </template>
      </l-layout>
    </div>
    <Preview
      v-show="isPreview"
      :pageSchema="printSchema"
      @close="handleClosePreview"
    ></Preview>

    <!-- 数据模型添加 -->
    <l-codetable-selectdialog
      :visible.sync="dbtableVisible"
      @select="dbTableSelect"
    >
    </l-codetable-selectdialog>
  </div>
</template>
<script>
const api = window.$api.print.printTemplate;
import ComponentLayer from "./formComponent/layer";
import ComponentDbTable from "./formComponent/dbTable";
import HeaderTool from "./formComponent/headerTool";
import FooterTool from "./formComponent/footerTool";
import BodyDesign from "./formComponent/bodyDesign";
import PageConfig from "./formComponent/pageConfig";

import Preview from "./preview";
import components from "./config/component";

import { getPageHeight, getPageWidth } from "./config/util";
import pageInitConfig from "./config/page";

import "./components/base";
export default {
  components: {
    ComponentLayer,
    ComponentDbTable,
    HeaderTool,
    FooterTool,
    BodyDesign,
    PageConfig,

    Preview,
  },
  data() {
    return {
      ready: false,
      isLayer: true,
      dbtableVisible: false,
      dbtableList: [],

      scale: 100,
      gridShow: false,
      gridSize: 20,
      ruleShow: true,

      components: components,
      pageActive: 0,
      activeObj: null,
      
      pageInitConfig: pageInitConfig,
      printSchema: {
        pageConfig: {},
        pages: [
          {
            components: [],
          },
        ],
      },
      isPreview: false,
    };
  },
  computed: {
    pages() {
      return this.printSchema.pages;
    },
    pageActiveObj() {
      return this.pages[this.pageActive];
    },
    pageConfig() {
      return this.printSchema.pageConfig;
    },
    pageHeight() {
      if (this.pageConfig.direction == "1") {
        return this._pageHeight;
      } else {
        return this._pageWidth;
      }
    },
    pageWidth() {
      if (this.pageConfig.direction == "1") {
        return this._pageWidth;
      } else {
        return this._pageHeight;
      }
    },

    _pageHeight() {
      return getPageHeight({
        pageType: this.pageConfig.pageType,
        height: this.pageConfig.pageHeight,
      });
    },
    _pageWidth() {
      return getPageWidth({
        pageType: this.pageConfig.pageType,
        width: this.pageConfig.pageWidth,
      });
    },

    apiCodeTable() {
      return window.$api.data.codeTable;
    },

    headerComponents() {
      return this.pages[0].components.filter((t) => t.config.isHeader);
    },
  },
  created() {
    this.printSchema.pageConfig = this.$deepClone(this.pageInitConfig);
    this.ready = true;
  },
  methods: {
    handleMenuClick(index) {
      if (index === "1") {
        this.isLayer = true;
      } else {
        this.isLayer = false;
      }
    },

    // 数据模型选择
    handOpenDbTable() {
      this.dbtableVisible = true;
    },
    async dbTableSelect(list, showLoading, hideLoading, dbCode) {
      showLoading();
      const tableList = [];
      const notAddTable = [];
      list.forEach((item) => {
        const table = {
          id: item.f_TableName,
          name: item.f_Description
            ? `${item.f_TableName}(${item.f_Description})`
            : item.f_TableName,
          comment: item.f_Description,
          isTable: true,
          children: [],
        };

        if (
          this.dbtableList.find((t) => {
            return t.id == table.id;
          }) == undefined
        ) {
          tableList.push(table);
        } else {
          notAddTable.push(table.name);
        }
      });

      if (tableList.length > 0) {
        const codeTables = await this.$awaitWraper(
          this.apiCodeTable.getList(dbCode, String(tableList.map((t) => t.id)))
        );
        for (const tableItem of tableList) {
          const codeTable = codeTables.find(
            (t) => t.lr_db_codetableEntity.f_TableName == tableItem.id
          );
          tableItem.children = codeTable.lr_db_codecolumnsList.map((t) => ({
            id: t.f_DbColumnName,
            name: t.f_Description
              ? `${t.f_DbColumnName}(${t.f_Description})`
              : t.f_DbColumnName,
            coment: t.f_Description,
          }));
          this.dbtableList.push(tableItem);
        }
      }

      if (notAddTable.length > 0) {
        this.$message({
          message: `${this.$t('重复添加表')}【${String(notAddTable)}】`,
          type: "warning",
        });
      }

      this.dbtableVisible = false;
      hideLoading();
    },
    deleteDbTable(index) {
      this.dbtableList.splice(index, 1);
    },

    // 组件新增，复制，删除，选中
    addComponent(type) {
      const obj = this.components.find((t) => t.type == type);
      const addObj = {
        label: obj.label,
        type: obj.type,
        icon: obj.icon,
      };
      addObj.config = this.$deepClone(obj.config);

      addObj.config.id = this.$uuid();
      addObj.config.label = obj.label;
      addObj.config.componentType = obj.type;

      //this.pageActiveObj.components.splice(0,0,addObj);//.push(addObj);
      this.pageActiveObj.components.push(addObj);
      this.activeObj = addObj;
    },
    copyComponent({ component, index }) {
      component.config.id = this.$uuid();
      component.config.label = `${component.config.label}${ this.$t('【复制】')}`;
      this.pageActiveObj.components.splice(index + 1, 0, component);
      this.activeObj = component;
    },
    deleteComponent(index) {
      if (
        this.activeObj &&
        this.pageActiveObj.components[index].config.id ==
          this.activeObj.config.id
      ) {
        if (index > 0) {
          this.activeObj = this.pageActiveObj.components[index - 1];
        } else if (this.pageActiveObj.components.length > 1) {
          this.activeObj = this.pageActiveObj.components[index + 1];
        } else {
          this.activeObj = null;
        }
      }

      this.pageActiveObj.components.splice(index, 1);
    },
    setComponentActive(component) {
      this.activeObj = component;
    },
    setComponentValue({ prop, value }) {
      this.$set(this.activeObj.config, prop, value);
    },
    clearComponents() {
      this.activeObj = null;
      this.pageActiveObj.components = [];
    },

    openPreview() {
      this.isPreview = true;
    },
    handleClosePreview() {
      this.isPreview = false;
    },

    getForm(type) {
      const postData = {};
      postData.lrPrintTemplateinfoEntity = this.$refs.pageConfigForm.getForm();

      const schema = this.$deepClone(this.printSchema);
      schema.pages.forEach((page) => {
        const components = [];
        page.components.forEach((component) => {
          components.push(component.config);
        });
        page.components = components;
      });

      schema.dbTables = this.$deepClone(this.dbtableList);
      postData.lrPrintTemplateEntity = {
        f_Type: type,
        f_Component: JSON.stringify(schema),
      };

      return postData;
    },
    async loadFormData({ keyValue, formCopy }) {
      if (keyValue) {
        const data = await this.$awaitWraper(api.get(keyValue));
        //复制操作
        if (formCopy) {
          data.lrPrintTemplateinfoEntity.f_Id = "";
          data.lrPrintTemplateinfoEntity.f_TemplateId = "";
          data.lrPrintTemplateinfoEntity.f_Name = `${data.lrPrintTemplateinfoEntity.f_Name}-${this.$t('复制')}`;
          data.lrPrintTemplateinfoEntity.f_Code = `${data.lrPrintTemplateinfoEntity.f_Code}-copy`;
          data.lrPrintTemplateEntity.f_Id = "";
          data.lrPrintTemplateEntity.f_TemplateInfoId = "";
        }
        this.setForm(data);
      }
    },
    setForm(data) {
      if (data.lrPrintTemplateEntity) {
        const schema = JSON.parse(data.lrPrintTemplateEntity.f_Component);
        schema.pages.forEach((page) => {
          const components = [];
          page.components.forEach((config) => {
            const component = this.components.find(
              (t) => t.type == config.componentType
            );
            const _component = {
              label: component.label,
              type: component.type,
              icon: component.icon,
              config: config,
            };

            components.push(_component);
          });
          page.components = components;
        });

        this.printSchema.pageConfig = schema.pageConfig;
        this.printSchema.pages = schema.pages;
        this.dbtableList = schema.dbTables;
      }
      if (data.lrPrintTemplateinfoEntity) {
        this.$refs.pageConfigForm.setForm(data.lrPrintTemplateinfoEntity);
      }
    },
    resetForm() {
      this.$refs.pageConfigForm.resetForm();

      this.ready = false;
      this.printSchema = {
        pageConfig: this.$deepClone(this.pageInitConfig),
        pages: [
          {
            components: [],
          },
        ],
      };
      this.pageActive = 0;
      this.activeObj = null;
      this.dbtableList = [];
      this.isPreview = false;

      this.ready = true;
    },
    // 校验表单
    async validateForm() {
      return this.$refs.pageConfigForm.validateForm();
    },
    async saveForm({ keyValue, isEdit, type }) {
      const postData = this.getForm(type);

      if (isEdit) {
        return await this.$awaitWraper(api.update(keyValue, postData));
      } else {
        return await this.$awaitWraper(api.add(postData));
      }
    },
  },
};
</script>
<style lang="scss">
.print-form {
  &__components {
    position: absolute;
    top: 0;
    left: 0;
    height: 100%;
    width: 56px;
    background-color: #fff;
  }

  .search-input .el-input__inner {
    height: 32px;
    background: #eeeeee;
    border-radius: 16px 16px 16px 16px;
    font-size: 14px;
  }
}
.print-form-design {
  padding-left: 56px;
  .el-menu-item .el-tooltip {
    padding: 0 !important;
  }
  .el-menu-item {
    padding: 0 !important;
  }
  .el-menu--collapse {
    width: 56px;
    border: none;
  }
}
.print-page-config-panel {
  padding: 16px 8px 0 8px;
  .print-config-title {
    font-size: 14px;
    font-weight: bold;
    color: #333;
  }

  .el-input__inner {
    border: none;
    border-bottom: 1px solid #dddddd;
    border-radius: 0;
    background-color: transparent;
  }

  .form-item-label-pd8 {
    .el-form-item__label {
      padding-left: 8px;
    }
  }
  .el-input__inner[type="Number"] {
    padding-right: 0 !important;
  }

  .el-select {
    .el-input__suffix {
      right: 0 !important;
      .el-select__caret {
        font-size: 12px !important;
        width: 16px;
      }
    }
  }
}

.print-form .el-input--mini .el-input__inner {
  height: 24px;
  line-height: 24px;
}

.print-form .el-slider__runway {
  background-color: #dddddd;
  height: 3px;
}

.print-form .el-slider__bar {
  height: 3px;
}

.print-form .el-slider__button-wrapper {
  top: -17px;
}

.print-form .el-slider__bar {
  background-color: #999999 !important;
}

.print-form .el-slider__button {
  width: 8px !important;
  height: 8px !important;
  border: solid 2px #9999 !important;
}

.print-form .el-input-number.is-controls-right .el-input-number__decrease,
.print-form .el-input-number.is-controls-right .el-input-number__increase {
  border: 0;
  width: 16px;
  background-color: inherit;
}
.print-form .el-input-number.is-controls-right .el-input__inner {
  padding-right: 16px;
}

.print-form .l-img-select__item {
  width: 80px;
  height: 80px;
}
.print-form .l-img-select__btn {
  width: 80px;
  height: 80px;
}
</style>
